import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt

# 读取CSV文件
csv_file = 'boston_housing.csv'
df = pd.read_csv(csv_file)

# 查看数据
print(df.head())

# 划分特征和目标变量
X = df.drop('MEDV', axis=1)  # 特征变量
y = df['MEDV']               # 目标变量

# 划分训练集和测试集
x_train, x_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=666)

# 创建线性回归模型
model = LinearRegression()

# 训练模型
model.fit(x_train, y_train)

# 打印模型系数和截距
print('多元线性回归模型系数：\n', model.coef_)
print('多元线性回归模型常数项：', model.intercept_)

# 预测测试集
y_pred = model.predict(x_test)

# 计算均方误差和R²分数
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
print('均方误差 (MSE):', mse)
print('R²分数:', r2)

# 可视化预测结果与实际结果
plt.scatter(y_test, y_pred, color='blue', label='Predicted vs Actual')
plt.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=2, label='Perfect Fit')
plt.xlabel('Actual')
plt.ylabel('Predicted')
plt.title('Actual vs Predicted Prices')
plt.legend()
plt.show()

# 可选：将预测结果与实际结果进行比较
df_results = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
print(df_results.head())